import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/providers/app_providers.dart';
import '../../core/types/app_types.dart';

/**
 * 通知覆盖层组件
 * 显示应用内通知消息
 */
class NotificationOverlay extends ConsumerWidget {
  const NotificationOverlay({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final notifications = ref.watch(notificationNotifierProvider);
    
    if (notifications?.isEmpty ?? true) {
      return const SizedBox.shrink();
    }

    return Positioned(
      top: 16,
      right: 16,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: notifications!.map((notification) {
          return Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: _NotificationCard(
              notification: notification,
              onDismiss: () {
                ref.read(notificationNotifierProvider.notifier).removeNotification(notification.id);
              },
            ),
          );
        }).toList(),
      ),
    );
  }
}

/**
 * 通知卡片组件
 */
class _NotificationCard extends StatefulWidget {
  final AppNotification notification;
  final VoidCallback onDismiss;

  const _NotificationCard({
    required this.notification,
    required this.onDismiss,
  });

  @override
  State<_NotificationCard> createState() => _NotificationCardState();
}

class _NotificationCardState extends State<_NotificationCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(1.0, 0.0),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOutCubic,
    ));
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeOut,
    ));
    
    // 开始动画
    _animationController.forward();
    
    // 自动消失
    if (widget.notification.duration != null) {
      Future.delayed(widget.notification.duration!, () {
        if (mounted) {
          _dismiss();
        }
      });
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _slideAnimation,
      child: FadeTransition(
        opacity: _fadeAnimation,
        child: Material(
          elevation: 8,
          borderRadius: BorderRadius.circular(8),
          child: Container(
            width: 320,
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: _getBackgroundColor(context),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: _getBorderColor(context),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                // 图标
                Icon(
                  _getIcon(),
                  color: _getIconColor(context),
                  size: 24,
                ),
                
                const SizedBox(width: 12),
                
                // 内容
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (widget.notification.title != null) ...[
                        Text(
                          widget.notification.title!,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: _getTextColor(context),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                      ],
                      Text(
                        widget.notification.message,
                        style: TextStyle(
                          fontSize: 13,
                          color: _getTextColor(context).withOpacity(0.9),
                        ),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
                
                // 关闭按钮
                IconButton(
                  onPressed: _dismiss,
                  icon: Icon(
                    Icons.close,
                    size: 18,
                    color: _getTextColor(context).withOpacity(0.7),
                  ),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(
                    minWidth: 24,
                    minHeight: 24,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /**
   * 获取通知图标
   */
  IconData _getIcon() {
    switch (widget.notification.type) {
      case NotificationType.success:
        return Icons.check_circle_outline;
      case NotificationType.error:
        return Icons.error_outline;
      case NotificationType.warning:
        return Icons.warning_outlined;
      case NotificationType.info:
        return Icons.info_outline;
    }
  }

  /**
   * 获取背景颜色
   */
  Color _getBackgroundColor(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    
    switch (widget.notification.type) {
      case NotificationType.success:
        return isDark ? Colors.green.shade900 : Colors.green.shade50;
      case NotificationType.error:
        return isDark ? Colors.red.shade900 : Colors.red.shade50;
      case NotificationType.warning:
        return isDark ? Colors.orange.shade900 : Colors.orange.shade50;
      case NotificationType.info:
        return isDark ? Colors.blue.shade900 : Colors.blue.shade50;
    }
  }

  /**
   * 获取边框颜色
   */
  Color _getBorderColor(BuildContext context) {
    switch (widget.notification.type) {
      case NotificationType.success:
        return Colors.green.shade300;
      case NotificationType.error:
        return Colors.red.shade300;
      case NotificationType.warning:
        return Colors.orange.shade300;
      case NotificationType.info:
        return Colors.blue.shade300;
    }
  }

  /**
   * 获取图标颜色
   */
  Color _getIconColor(BuildContext context) {
    switch (widget.notification.type) {
      case NotificationType.success:
        return Colors.green.shade600;
      case NotificationType.error:
        return Colors.red.shade600;
      case NotificationType.warning:
        return Colors.orange.shade600;
      case NotificationType.info:
        return Colors.blue.shade600;
    }
  }

  /**
   * 获取文本颜色
   */
  Color _getTextColor(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    
    switch (widget.notification.type) {
      case NotificationType.success:
        return isDark ? Colors.green.shade100 : Colors.green.shade800;
      case NotificationType.error:
        return isDark ? Colors.red.shade100 : Colors.red.shade800;
      case NotificationType.warning:
        return isDark ? Colors.orange.shade100 : Colors.orange.shade800;
      case NotificationType.info:
        return isDark ? Colors.blue.shade100 : Colors.blue.shade800;
    }
  }

  /**
   * 关闭通知
   */
  void _dismiss() async {
    await _animationController.reverse();
    widget.onDismiss();
  }
}